package com.example.inetSocketAddress;

import org.junit.jupiter.api.Test;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @Author 郅占伟
 * @ClassName TestInetAddress
 * @Description TODO
 * @Date 2024年05月25日
 * @Version: 1.0
 */
public class TestInetSocketAddress {

    /**
     * @Author 郅占伟
     * @Description 使用主机名加端口号获取InetSocketAddress对象
     * @MethodName testInetSocketAddress
     * @Date 9:20 2024/5/25
     */
    @Test
    public void getInetSocketAddressHostName() {
        // 创建InetSocketAddress对象
        InetSocketAddress address = new InetSocketAddress("localhost", 8080);
        // 获取主机名
        String hostname = address.getHostName();
        // 获取端口号
        int port = address.getPort();
        // 输出结果
        System.out.println("Hostname: " + hostname);
        System.out.println("Port: " + port);
    }

    @Test
    public void getInetSocketAddressInetAddress() throws UnknownHostException {
        // 解析域名获取 IP 与主机信息
        InetAddress inetAddress = InetAddress.getByName("localhost");

        // 端口号
        int port = 8080;

        // 创建InetSocketAddress对象
        InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, 8080);

        InetAddress address = inetSocketAddress.getAddress();        // 获取主机域名
        String hostString = inetSocketAddress.getHostString();      // 获取主机名
        String hostName = inetSocketAddress.getHostName();          // 获取主机名

        int port1 = inetSocketAddress.getPort();

        System.out.println("Address: " + address.toString());
        System.out.println("HostString: " + hostString);
        System.out.println("HostName: " + hostName);
        System.out.println("Port: " + port1);
    }
}
